package consul

import (
	"fmt"
	"github.com/hashicorp/consul/api"
)

//Register service into consul
func Register(address string, ip string, port int, serviceName string, healthCheck string) (err error) {
	config := api.DefaultConfig()
	config.Address = address
	// Get a new client
	client, err := api.NewClient(config)
	if err != nil {
		return
	}
	agent := client.Agent()
	agentCheck := &api.AgentServiceCheck{
		Interval:                       "5s",
		Timeout:                        "3s",
		DeregisterCriticalServiceAfter: "30s",
	}
	if len(healthCheck) > 0 {
		agentCheck.HTTP = fmt.Sprintf("http://%s:%d%s", ip, port, healthCheck)
	} else {
		agentCheck.GRPC = fmt.Sprintf("%v:%v/%v", ip, port, serviceName)
	}
	reg := &api.AgentServiceRegistration{
		Kind:    "",
		ID:      fmt.Sprintf("%v-%v-%v", serviceName, ip, port),
		Name:    serviceName,
		Tags:    nil,
		Port:    port,
		Address: ip,
		Check:   agentCheck,
	}
	err = agent.ServiceRegister(reg)
	return
}

type Service struct {
	ServiceId string
	ServiceName string
	Address string
	Port int
	ServiceMeta map[string]string
}

func GetService(address string,serviceId string) ([]Service,error) {
	config := api.DefaultConfig()
	config.Address = address
	// Get a new client
	client, err := api.NewClient(config)
	if err != nil {
		return nil,err
	}
	catelogService,_,_:=client.Catalog().Service(serviceId,"",nil)
	if len(catelogService)>0{
		result:=make([]Service,len(catelogService))
		for i,v:=range catelogService{
			s:=Service{
				ServiceId:   v.ServiceID,
				ServiceName: v.ServiceName,
				Address:     v.Address,
				Port:        v.ServicePort,
				ServiceMeta: v.ServiceMeta,
			}
			result[i]=s
		}
		return result,nil
	}
	return nil,nil
}
